package com.gopay.checkorder.service.impl.bcdl;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.manager.order.CpsGeneralMainOrderQueryManager;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.trace.anotation.GopayTracer;
import com.gopay.common.util.HttpTransport;
import com.gopay.gass.service.GassPayRemoteService;
import com.gopay.remote.order.BcdlCheckOrderRemoteService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zyt on 2017/8/4.
 * 单独对自动结算银企直联做业务
 */
@Service("bcdlBankOrderService")
public class BcdlBankOrderServiceImpl implements BankOrderService, BcdlCheckOrderRemoteService {

    private final static Logger logger = LoggerFactory.getLogger(BcdlBankOrderServiceImpl.class);

    @Resource(name = "bcdlCheckOrderProxy")
    private BankOrderService bcdlCheckOrderProxy;

    @Resource(name = "cpsGeneralMainOrderQueryManager")
    private CpsGeneralMainOrderQueryManager mainOrderQuery;
    @Resource(name = "gassPayService")
    private GassPayRemoteService gassPayService;
    @Override
    @GopayTracer(orderIdSpel = "#bankOrder.orderId")
    public CheckOrderResult checkOrder(BankOrder bankOrder, String bankOrderStatus) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();

        if (bankOrder == null) {
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5060);
            checkOrderResult.setErrMsg("银行订单为空");
            logger.error("bankOrder is null.");
            return checkOrderResult;
        }

        if(!statusPreCheck(bankOrder.getOrderId())){
            logger.error("订单状态不正确，对账失败，orderID=" + bankOrder.getOrderId());
            checkOrderResult.setSuccess(false);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5042);
            checkOrderResult.setErrMsg("订单状态异常");
            return checkOrderResult;
        }

        logger.error("BankOrder:" + bankOrder);
        checkOrderResult = bcdlCheckOrderProxy.checkOrder(bankOrder, bankOrderStatus);

        return checkOrderResult;
    }

    @Override
    @GopayTracer(orderIdSpel = "#bankOrder.orderId")
    public CheckOrderResult checkOrderWithDoAcct(BankOrder bankOrder, String bankOrderStatus){
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        HttpTransport notifyGass = new HttpTransport();
        notifyGass.setSendEncoding("UTF-8");
        notifyGass.setUrl(bankOrder.getRemark2());
        Map<String, String> param = new HashMap<String, String>();
        //add by zyt,2017-9-11，如果当前银行订单表状态为02,03,04，则直接走成功流程，如果为11，则直接返回异常
        try {
            if(StringUtils.equals(bankOrder.getOrderStatus(), BankOrderStatus.AUTO_CHECK_SUCCESS) ||
                    StringUtils.equals(bankOrder.getOrderStatus(), BankOrderStatus.BANK_CALL_SUCCESS) ||
                    StringUtils.equals(bankOrder.getOrderStatus(), BankOrderStatus.CHECK_SUCCESS)){
                logger.info("对账成功，银行订单已经成功，直接揍成功流程，不发往银行,orderId=" + bankOrder.getOrderId());
                checkOrderResult.setSuccess(true);
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100S1000);
                param.put("resultCode", "1");
                param.put("gopayOrderId", bankOrder.getOrderId());
                //notifyGass.submit(param); 生产优化10期 lx httpclient 替换为 hessian
                gassPayService.bcdlNotifyGass(param);
                return checkOrderResult;
            } else if(StringUtils.equals(bankOrder.getOrderStatus(), BankOrderStatus.ACCEPTED) || !statusPreCheck(bankOrder.getOrderId())){
                logger.info("对账失败，订单状态错误，orderId=" + bankOrder.getOrderId());
                checkOrderResult.setSuccess(false);
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5042);
                checkOrderResult.setErrMsg("订单状态异常");
                return checkOrderResult;
            }
        }catch (Exception e){
            logger.error("通知做账异常:", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100F1002);
            checkOrderResult.setErrMsg("通知做账异常");
            return checkOrderResult;
        }
        checkOrderResult = checkOrder(bankOrder, bankOrderStatus);
        //notifyGass.setUrl("http://localhost:8080/gass/notify/bcdlNotify.shtml");
        try {
            if (ProcCodeConstants.PROC_CODE_100E6027.equals(checkOrderResult.getErrCode())) {
                param.put("resultCode", "2");
                param.put("resultMsg", checkOrderResult.getErrMsg());
                param.put("gopayOrderId", bankOrder.getOrderId());
                //是否需要做失败的拒绝账务，目前只支持工行
                if(checkOrderResult.isNeedRefund()){
                    logger.info("发起失败拒绝账务：orderId:" + bankOrder.getOrderId());
                    param.put("needRefund", "1");
                }
                //notifyGass.submit(param); 生产优化10期 lx httpclient 替换为 hessian
                gassPayService.bcdlNotifyGass(param);
            } else if (checkOrderResult.isSuccess()) {
                param.put("resultCode", "1");
                param.put("gopayOrderId", bankOrder.getOrderId());
                //notifyGass.submit(param); 生产优化10期 lx httpclient 替换为 hessian
                gassPayService.bcdlNotifyGass(param);
            } else {
                param.put("resultCode", "3");
                param.put("gopayOrderId", bankOrder.getOrderId());
                //notifyGass.submit(param); 生产优化10期 lx httpclient 替换为 hessian
                gassPayService.bcdlNotifyGass(param);
            }
        }catch (Exception e){
            logger.error("通知做账异常:", e);
        }
        return checkOrderResult;
    }

    /**
     * add by zyt,校验当前订单的主订单状态，如果为终态，则不去对单，直接置失败
     * @param gopayOrderId
     * @return
     */
    private boolean statusPreCheck(String gopayOrderId){
        CpsGenMainOrder mainOrder = mainOrderQuery.get(gopayOrderId);
        if(mainOrder == null){
            return false;
        }
        int txnStaCd = mainOrder.getTxnStaCd();
        if(TxnStaCode.TXN_STA_CD_20000.value != txnStaCd &&
           TxnStaCode.TXN_STA_CD_20001.value != txnStaCd &&
           TxnStaCode.TXN_STA_CD_20002.value != txnStaCd &&
           TxnStaCode.TXN_STA_CD_20003.value != txnStaCd &&
           TxnStaCode.TXN_STA_CD_20004.value != txnStaCd){
            return true;
        }

        return false;
    }

    @Override
    public BankOrder getDbOrder() {
        return null;
    }

    @Override
    public BaseMessage dayend(String bank_bus) {
        return null;
    }

    @Override
    public Result getDayendMsg(String string) {
        return null;
    }

    @Override
    public List<CheckOrderResult> checkDayend(String bank_bus) {
        return null;
    }

    @Override
    public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
        return null;
    }

}
